import { FormMethods, FormMethodsLocal, FormProps } from "../types"

export function useForm(props?: Partial<FormProps>) {
    const formRef = ref<Nullable<FormMethodsLocal>>(null)
    const loadedRef = ref<boolean>(false)

    function register(instance: FormMethodsLocal) {
        onUnmounted(() => {
            formRef.value = null
            loadedRef.value = false
        })
        if (unref(loadedRef)) {
            return
        }
        formRef.value = instance
        loadedRef.value = true

        watch(
            () => props,
            () => {
                props && instance.setProps(props)
            },
            {
                immediate: true,
                deep: true
            }
        )
    }

    async function getForm() {
        const form = unref(formRef)
        if (!form) {
            console.error(
                "The form instance has not been obtained, please make sure that the form has been rendered when performing the form operation!"
            )
        }
        await nextTick()
        return form as FormMethods
    }

    const methods: FormMethods = {
        getFormData: () => {
            return unref(formRef)?.getFormData() ?? {}
        },
        setFormData: async data => {
            const form = await getForm()
            form.setFormData(data)
        },
        setFormItemData: async data => {
            const form = await getForm()
            form.setFormItemData(data)
        },
        setDefaultFormData: async data => {
            const form = await getForm()
            form.setDefaultFormData(data)
        },
        validate: async cb => {
            const form = await getForm()
            form.validate(cb)
        },
        clearValidate: async () => {
            const form = await getForm()
            form.clearValidate()
        },
        resetForm: async () => {
            const form = await getForm()
            form.resetForm()
        }
    }

    return { register, methods }
}
